﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Diagnostics.Contracts;
using System.Web.Routing;
using System.Linq.Expressions;

namespace FoundationLib.Web.Mvc
{
	public static class CheckBoxHelper
	{
		public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, 
			IEnumerable<CheckBoxListItem> items, IEnumerable<string> checkedValues, object htmlAttributes)
		{
			Contract.Requires(!String.IsNullOrWhiteSpace(name));
			Contract.Requires(items != null);

			StringBuilder sb = new StringBuilder();
			foreach (CheckBoxListItem item in items)
			{
				TagBuilder tag = new TagBuilder("input");
				tag.MergeAttribute("type", "checkbox");
				tag.MergeAttribute("name", name);
				if (htmlAttributes != null)
					tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
				tag.MergeAttribute("value", item.Value);
				if (checkedValues != null && checkedValues.Contains(item.Value))
					tag.MergeAttribute("checked", "checked");
				tag.InnerHtml = item.Text;
				sb.Append(tag.ToString(TagRenderMode.Normal)).Append("<br/>");
			}

			return MvcHtmlString.Create(sb.ToString());
		}

		public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<CheckBoxListItem> items, 
			IEnumerable<string> checkedValues)
		{
			return CheckBoxList(helper, name, items, checkedValues, null);
		}

		public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<CheckBoxListItem> items, object htmlAttributes)
		{
			string name = System.Web.Mvc.ExpressionHelper.GetExpressionText(expression);
			IEnumerable<string> checkedValues = expression.Compile().Invoke(helper.ViewData.Model) as IEnumerable<string>;
			return CheckBoxList(helper, name, items, checkedValues, htmlAttributes);
		}

		public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<CheckBoxListItem> items)
		{
			return CheckBoxListFor(helper, expression, items, null);
		}
	}
}
